import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv, type ConfigEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import fs from 'fs'
import path from 'path'

function autoImportI18nPlugin() {
  return {
    name: 'auto-import-i18n',
    transformIndexHtml(html: string) {
      const publicDir = path.resolve('public')
      const i18nDir = path.join(publicDir, 'i18n')

      if (!fs.existsSync(i18nDir)) {
        console.warn('[auto-import-i18n] i18n directory not found:', i18nDir)
        return html
      }

      const files = fs.readdirSync(i18nDir).filter((file) => file.endsWith('.js'))
      const scripts = files
        .map((file) => {
          // public 目录下的资源直接通过绝对路径引用
          return `    <script defer src="/i18n/${file}"></script>`
        })
        .join('\n')

      // 将生成的 script 标签插入到 body 结束标签前
      return html.replace('</title>', `</title>\n${scripts}`)
    },
  }
}

// https://vite.dev/config/
const viteConfig = defineConfig((mode: ConfigEnv) => {
  const env = loadEnv(mode.mode, process.cwd()) as unknown as {
    VITE_PORT: number
  }

  const local = {
    en: { name: 'English', module: 'en', defaultSeleted: false },
    'zh-cn': { name: '简体中文', module: 'zh-cn', defaultSeleted: false },
    'zh-tw': { name: '繁体中文', module: 'zh-tw', defaultSeleted: false },
    bjrm: { name: '北京人民', module: 'zh-cn', defaultSeleted: false },
  }

  fs.writeFileSync('./public/local.js', `window.__env__.local = ${JSON.stringify(local, null, 2)}`)

  return {
    plugins: [vue(), vueJsx(), vueDevTools(), autoImportI18nPlugin()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      host: '0.0.0.0',
      port: env.VITE_PORT as unknown as number,
      open: false,
      hmr: true,
    },
  }
})

export default viteConfig
